const path = require("path");
const os = require("os");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 样式分离
const { VueLoaderPlugin } = require("vue-loader"); // 引入 vue-loader 插件

const AutoImport = require("unplugin-auto-import/webpack").default;
const Components = require("unplugin-vue-components/webpack").default;
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");

// 打包版本信息
const version = require("./version");

module.exports = (isDev = true) => {
  // 正式环境用 MiniCssExtractPlugin.loader 实现样式分离
  const styleLoader = isDev ? "style-loader" : MiniCssExtractPlugin.loader;

  return {
    entry: path.resolve(__dirname, "../src/main.ts"),

    output: {
      path: path.resolve(__dirname, "../dist"),
      filename: "js/[name]-[fullhash].js",
      chunkFilename: "js/[name].[chunkhash].js",
    },

    resolve: {
      alias: {
        "@": path.resolve(__dirname, "../src"),
      },
      extensions: [".ts", ".js", ".vue"],
    },

    module: {
      rules: [
        {
          test: /\.vue$/,
          loader: "vue-loader",
        },

        {
          test: /\.tsx?$/, // 匹配 TypeScript 文件
          exclude: /node_modules/, // 排除 node_modules 目录
          use: [
            {
              loader: "ts-loader",
              options: {
                transpileOnly: true, // 只进行转译，不进行类型检查
                appendTsSuffixTo: [/\.vue$/],
              },
            },
          ],
        },

        {
          test: /\.jsx?$/, // 匹配所有 .js|.jsx 文件
          exclude: /node_modules/, // 排除 node_modules 文件夹中的代码
          use: [
            {
              loader: "babel-loader",
            },
          ],
        },

        {
          test: /\.css$/,
          use: [styleLoader, "css-loader", "postcss-loader"],
        },

        {
          test: /\.scss$/,
          exclude: /node_modules/, // 排除 node_modules 目录
          use: [styleLoader, "css-loader", "sass-loader", "postcss-loader"],
        },
      ],
    },

    plugins: [
      // 使用 html-webpack-plugin 插件生成 HTML 文件
      new HtmlWebpackPlugin({
        template: "./public/index.html", // 模板文件，路径先对于根目录
        filename: "index.html", // 生成的 HTML 文件名
        inject: "body", // 将 JS 插入到 <body> 标签中
        templateParameters: {
          builtTime: version.builtTime,
          GitBranch: version.currentGitBranch,
        },
      }),

      new VueLoaderPlugin(),

      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),

      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],

    // parallelism: Math.max(os.cpus().length - 1, 1),
  };
};
